//
//  RHLocalFaultAlarmListVC.m
//  RuiHeAppApp
//
//  Created by Yan Chen on 2024/4/9.
//

#import "RHLocalFaultAlarmListVC.h"
#import "RHLocalFaultAlarmListCell.h"
#import "RHDeviceAlarmModel.h"
#import "RHLocalFaultAlarmDetailVC.h"

@interface RHLocalFaultAlarmListVC ()<UITableViewDelegate,UITableViewDataSource,UISearchResultsUpdating, UISearchBarDelegate>
@property (nonatomic, strong) UISearchController *searchController;

@property (nonatomic ,strong) UIView *seacrhView;

@property (nonatomic ,strong) UIView *touchView;

@property (nonatomic ,strong) UITableView *resultTableView;

@property (nonatomic ,strong) UITableView *tableView;

@property (nonatomic ,strong) NSMutableArray *searchList;//搜索结果

@property (nonatomic ,strong) NSMutableArray *alarmListArray;


//1:告警  2:故障
@property (nonatomic, assign) NSInteger faultLevel;

@property (nonatomic, copy) NSString *deviceId;

@property (nonatomic, assign) RequestType requestType;
//当前页数
@property (nonatomic, assign) NSInteger currentPage;
//总页数
@property (nonatomic, assign) NSInteger totalPage;
//每页多少条数据
@property (nonatomic, assign) NSInteger numOfPage;

@end

@implementation RHLocalFaultAlarmListVC

-(id)initWithLevel:(NSInteger)level deviceId:(NSString*)deviceId
{
    self = [super init];
    if(self){
        _faultLevel = level;
        _deviceId = deviceId;
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = CFTabViewBgColor;
    self.currentPage = 1;
    self.numOfPage = 5;
    self.requestType = RequestTypeRefresh;
    [self getAlarmOrFaultList];
    [self setupUI];
}

#pragma mark ---- 获取故障列表 -----
-(void)getAlarmOrFaultList{
    [QMUITips showLoadingInView:self.view];
    NSMutableDictionary *para = @{@"pageNum":@(self.currentPage),
                           @"pageSize":@(self.numOfPage),
                           @"faultLevelList":@[@(self.faultLevel)]}.mutableCopy;

    if(self.deviceId.length>0){
        [para setObject:self.deviceId forKey:@"deviceId"];
    }
    
    [RHDeviceAlarmModel startGetWithCompletionAPIKey:H_deviceLogList argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
            NSInteger total = [request.responseObject[@"total"] integerValue];
            self.totalPage = total%self.numOfPage? total/self.numOfPage+1 : total/self.numOfPage;
            NSMutableArray *arr = [NSMutableArray arrayWithArray:resultModel.data];
            //下拉刷新
            if(self.requestType == RequestTypeRefresh){
                [self.tableView endHeaderRefresh];
                self.alarmListArray = arr;
            }else{//上拉加载
                [self.tableView endFooterRefresh];
                [self.alarmListArray addObjectsFromArray:arr];
            }
            if(self.currentPage >= self.totalPage){
                [self.tableView endFooterRefreshCustomWithNoMoreData];
            }
            [self.tableView reloadData];
            
           
            if(self.alarmListArray.count == 0){
                [self.tableView endFooterRefreshWithNoMoreData];
            }
        }
      
        [self.tableView endHeaderRefresh];
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.tableView endHeaderRefresh];
        [self.tableView endFooterRefresh];
        
    }];
}

-(void)setupUI{
    kWeakSelf;
    _seacrhView = [[UIView alloc] init];
    _seacrhView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_seacrhView];
    
    // 创建UISearchController, 这里使用当前控制器来展示结果
    UISearchController *search = [[UISearchController alloc]initWithSearchResultsController:nil];
    //[search.view setBackgroundColor:BGMainColor];
    // 设置结果更新代理
    search.searchResultsUpdater = self;
    // 因为在当前控制器展示结果, 所以不需要这个透明视图
    search.dimsBackgroundDuringPresentation = NO;
    // 是否自动隐藏导航
    search.hidesNavigationBarDuringPresentation = NO;
    // 将searchBar赋值给tableView的tableHeaderView
    [search.searchBar setBackgroundColor:[UIColor whiteColor]];
    search.searchBar.delegate = self;

    search.searchBar.tintColor = CMainColorGreen;
    search.searchBar.barTintColor = [UIColor orangeColor];
    search.searchBar.placeholder = @"请输入设备ID".rh_localized;
    search.searchBar.qmui_font = kSYSTEMFONT(14);
    search.searchBar.searchBarStyle = UISearchBarStyleMinimal;
    [search.searchBar positionAdjustmentForSearchBarIcon:UISearchBarIconSearch];
    [search.searchBar setReturnKeyType:UIReturnKeyDone];
    //搜索框左边图片
    UIImageView *leftImg = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"search"]];
    leftImg.frame = CGRectMake(0, 0, 15, 15);
    if(@available(iOS 13.0,*)){
        search.searchBar.searchTextField.leftView = leftImg;
    }
    
    self.searchController = search;
    
    [_seacrhView addSubview:search.searchBar];
    // 改变UISearchBar内部输入框样式
    UIView *searchTextField = nil;
    searchTextField = [[[search.searchBar.subviews firstObject] subviews] lastObject];

    // 改变输入框背景色
    searchTextField.subviews[0].backgroundColor = [UIColor colorWithHexString:@"F6F8FA"];
    for (UIView *sub1 in searchTextField.subviews) {
        NSLog(@"111----->%@",NSStringFromClass([sub1 class]));
        for (UIView *sub2 in sub1.subviews) {
            NSLog(@"222----->%@",NSStringFromClass([sub2 class]));
            for (UIView *sub3 in sub2.subviews) {
                NSLog(@"333----->%@",NSStringFromClass([sub3 class]));
                if([sub3 isKindOfClass:NSClassFromString(@"_UISearchBarSearchFieldBackgroundView")]){
                    [sub3 removeFromSuperview];
                }
            }
        }
    }
    searchTextField.layer.cornerRadius = 5.0;
    
    
    _resultTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    [_resultTableView setBackgroundColor:CFTabViewBgColor];
    [_resultTableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [_resultTableView setSeparatorColor:UIColor.clearColor];
    [_resultTableView setDelegate:self];
    [_resultTableView setDataSource:self];
    [_resultTableView registerClass:[RHLocalFaultAlarmListCell class] forCellReuseIdentifier:@"RHLocalFaultAlarmListCell"];
    [search.view addSubview:_resultTableView];
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    [_tableView setBackgroundColor:CFTabViewBgColor];
    [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [_tableView setSeparatorColor:UIColor.clearColor];
    _tableView.estimatedRowHeight = 180;
    _tableView.rowHeight = UITableViewAutomaticDimension;
    _tableView.tableFooterView = [UIView new];
    [_tableView setDelegate:self];
    [_tableView setDataSource:self];
    [_tableView registerClass:[RHLocalFaultAlarmListCell class] forCellReuseIdentifier:@"RHLocalFaultAlarmListCell"];
    _tableView.ly_emptyView = [LYEmptyView emptyViewWithImageStr:@"nodata_icon_1" titleStr:@"没有数据".rh_localized detailStr:@""];
    [self.view addSubview:_tableView];
    if (@available(iOS 11.0, *)) {
        _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    
    if (@available(iOS 15.0, *)) {
        _tableView.sectionHeaderTopPadding = 0;
    }
    
  
    [_tableView addHeaderRefresh:^{
        [weakSelf.tableView.mj_footer resetNoMoreData];
        weakSelf.requestType = RequestTypeRefresh;
        weakSelf.currentPage = 1;
        [weakSelf getAlarmOrFaultList];
    }];
    [_tableView addBackFooterRefresh:^{
        weakSelf.requestType = RequestTypeAdd;
        weakSelf.currentPage++;
        [weakSelf getAlarmOrFaultList];
    }];
    
    _touchView = [[UIView alloc] init];
    [_touchView setBackgroundColor:UIColor.clearColor];
    [search.view addSubview:_touchView];
    
    //手势
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] init];
    [_touchView addGestureRecognizer:tap];
    [[tap rac_gestureSignal] subscribeNext:^(id x) {
        [weakSelf touchAction];
    }];
    
    [_touchView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsZero);
    }];
    
    [_seacrhView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_offset(0);
        make.left.right.mas_offset(0);
        make.height.mas_equalTo(60);
    }];
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_seacrhView.mas_bottom).offset(0);
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.bottom.equalTo(self.view).offset(-kSafe_bottom);
    }];
    
    
    [_resultTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        make.top.mas_offset(kNavHeight);
        make.bottom.mas_offset(0);
    }];
}

- (void)touchAction{
    if(self.searchList.count>0){
        [self.searchController.view endEditing:YES];
        [self.touchView setHidden:YES];
        [UIView animateWithDuration:0.4 animations:^{
            [self.seacrhView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.top.mas_offset(0);
            }];
        }];
    }else{
        [self.searchController setActive:NO];
        [UIView animateWithDuration:0.4 animations:^{
            [self.seacrhView.searchBar setBackgroundColor:BGColor];
            [self.seacrhView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.top.mas_offset(0);
            }];
        }];
    }
}




#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if([tableView isEqual: self.tableView]){
        return self.alarmListArray.count;
    }
    
    if([tableView isEqual:self.resultTableView]){
        return self.searchList.count;
    }
    
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 5;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return [UIView new];
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    
    return [UIView new];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    RHDeviceAlarmModel *alarmModel;
    if(tableView == self.resultTableView){
        alarmModel = self.searchList[indexPath.row];
    }else{
        alarmModel = self.alarmListArray[indexPath.row];
    }
    RHLocalFaultAlarmListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RHLocalFaultAlarmListCell"];
    cell.alarmModel = alarmModel;
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    RHLocalFaultAlarmDetailVC *detailVC = [[RHLocalFaultAlarmDetailVC alloc]init];
    [self.navigationController pushViewController:detailVC animated:YES];
}

#pragma mark - UISearchResultsUpdating
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController {
    NSString *inputStr = searchController.searchBar.text;
    if (self.searchList.count > 0) {
        [self.searchList removeAllObjects];
    }
    for (RHDeviceAlarmModel *model in self.alarmListArray) {
        if ([model.deviceId.lowercaseString rangeOfString:inputStr.lowercaseString].location != NSNotFound) {
            [self.searchList addObject:model];
        }
    }
    [self.resultTableView reloadData];
}

#pragma mark - UISearchBarDelegate
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{
    return YES;
}

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
    [self.touchView setHidden:NO];
    [UIView animateWithDuration:0.4 animations:^{
//        [searchBar setBackgroundColor:[UIColor whiteColor]];
        [self.view layoutIfNeeded];
        [self.tableView layoutIfNeeded];
        [self.seacrhView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.top.mas_offset(-kNavBarHeight);
        }];
    }];
}
- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar {
    return YES;
}

- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar {
    if(!self.searchController.active){
        [UIView animateWithDuration:0.4 animations:^{
//            [searchBar setBackgroundColor:BGColor];
            [self.seacrhView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.top.mas_offset(0);
            }];
        }];
    }
    
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    NSLog(@"");
    [self.touchView setHidden:YES];
    //[self.searchController setActive:NO];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    [self.searchController setActive:NO];
    [UIView animateWithDuration:0.4 animations:^{
//        [searchBar setBackgroundColor:BGColor];
        [self.seacrhView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.top.mas_offset(0);
        }];
    }];
}


- (UIView *)listView
{
    return self.view;
}


- (NSMutableArray *)alarmListArray{
    if (!_alarmListArray) {
        _alarmListArray = [NSMutableArray array];
    }
    return _alarmListArray;
}

- (NSMutableArray *)searchList{
    if(!_searchList){
        _searchList = [NSMutableArray array];
    }
    return _searchList;
}



@end
